﻿using machine_registration.Helpers;
using machine_registration.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Media3D;
using Wpf.Ui;

namespace machine_registration.ViewModels
{
    /// <summary>
    /// 设备入库管理
    /// </summary>
    public partial class ReturnPageViewModel : ViewModel
    {
        private readonly AppDbContext _db;
        private readonly ILogger<ReturnPageViewModel> _logger;
        [ObservableProperty]
        private DeviceInventory _newDevice = new();
        [ObservableProperty]
        private List<string> _OwnerId_list=new();
        // 设备类型选项集合 
        /// <summary>
        /// 设备类型选项
        /// </summary>
        public List<DeviceTypeOption> DeviceTypes { get; } = Enum.GetValues(typeof(DeviceType))
            .Cast<DeviceType>()
            .Select(t => new DeviceTypeOption(t))
            .ToList();
        public ReturnPageViewModel(AppDbContext dbContext, ILogger<ReturnPageViewModel> logger)
        {
            _db = dbContext;
            _db.Database.EnsureCreated(); // 自动创建数据库
            _logger = logger;
        }
        public override void OnNavigatedTo()
        {
            _logger.LogDebug("导航成功 ReturnPageViewModel");
            LoadCurrentKeepersAsync();
        }
        // 提交命令 
        [RelayCommand]
        private async Task Submit()
        {
      
            try
            {
                var validation = NewDevice.ValidateProperties();
                if (!validation.isok)
                {
                    await ShowDialog("验证失败", validation.erro);
                    return;
                }
                // 在唯一性校验前增加转换 
                NewDevice.MachineId = NewDevice.MachineId.ToUpperInvariant();

                // 唯一性校验前置 
                var existsQuery = _db.DeviceInventorys
                    .Where(x => x.MachineId == NewDevice.MachineId);

                if (await existsQuery.AnyAsync())
                {
                    var conflictDevice = await existsQuery.FirstAsync();
                    var conflictField = conflictDevice.MachineId == NewDevice.MachineId
                                      ? "SN号" : "序列号";

                    await ShowDialog("无法入库！",
                        $"该设备的{conflictField}与已入库设备（SN：{conflictDevice.MachineId}）重复");
                    return;
                }


                NewDevice.EntryDate = DateTime.Now; // 自动记录入库时间 
                NewDevice.Status = InventoryStatus.InStock; // 默认在库状态 
                NewDevice.InventoryId = 0;
                _db.DeviceInventorys.Add(NewDevice);
                await _db.SaveChangesAsync();

             
                await ShowDialog("入库成功", $"{NewDevice.DeviceName} 已成功登记入库");
                //Reset();
            }
            catch (DbUpdateException ex)
            {
                
                Debug.WriteLine($"数据保存失败：{ex.InnerException?.Message}");
          
            }
        }

        // 重置命令 
        [RelayCommand]
        private void Reset()
        {
            NewDevice = new DeviceInventory
            {
                EntryDate = DateTime.Now,
                Status = InventoryStatus.InStock
            };
        }


        /// <summary>
        /// 加载当前实际归属人列表
        /// </summary>
        /// <returns></returns>
        private void LoadCurrentKeepersAsync()
        {
            try
            {
                var keepers =  _db.DeviceInventorys
                    .Where(d => !string.IsNullOrEmpty(d.OwnerId))
                    .Select(d => d.OwnerId)
                    .Distinct()
                    .OrderBy(k => k)
                    .ToListAsync();

                Application.Current.Dispatcher.Invoke(() =>
                {
                    OwnerId_list.Clear();
                    foreach (var keeper in keepers.Result)
                    {
                        OwnerId_list.Add(keeper);
                    }
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"加载责任人列表失败: {ex.Message}");
            }
        }

        private async Task ShowDialog(string title, string content)
        {
            var dialog = new Wpf.Ui.Controls.MessageBox
            {
                Title = title,
                Content = content,
                CloseButtonText = "我已知晓"
            };
            await dialog.ShowDialogAsync();
        }
    }
}
